package com.xuanwei.web.controller;

import com.xuanwei.core.annos.Single;
import com.xuanwei.core.entity.vo.CartVo;
import com.xuanwei.core.response.ResultVO;
import com.xuanwei.core.service.IXwCartService;
import com.xuanwei.core.util.ParamUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/7/8 14:35
 **/
@RestController
@RequestMapping("wx/cart")
public class CartController extends BasicController {

    private IXwCartService cartService;


    public CartController(IXwCartService cartService) {
        this.cartService = cartService;
    }

    @Single()
    @RequestMapping(value = "addToCart", method = RequestMethod.GET)
    public ResultVO addCart(Integer skuId, Integer count) {
        if (!ParamUtil.checkIsPositiveInteger(skuId)) {
            return ResultVO.failResult("参数错误");
        }
        if (!ParamUtil.checkIsPositiveInteger(count)) {
            return ResultVO.failResult("参数错误");
        }
        cartService.add(skuId, count, getUserId());
        return ResultVO.successResult("添加成功");
    }


    @RequestMapping(value = "cartList", method = RequestMethod.GET)
    public ResultVO cartList() {
        List<CartVo> cartVos = cartService.cartList(getUserId());
        return ResultVO.successResult(cartVos);
    }


    @RequestMapping(value = "changeCount", method = RequestMethod.GET)
    public ResultVO changeCount(Integer id, Integer count) {
        if (!ParamUtil.checkIsPositiveInteger(id)) {
            return ResultVO.failResult("参数错误");
        }

        cartService.updateCount(id, count);
        return ResultVO.successResult("操作成功");
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public ResultVO delete(String id) {
        if (StringUtils.isBlank(id)) {
            return ResultVO.failResult("参数错误");
        }
        List<Integer> ids = Arrays.stream(id.split("-")).map(Integer::parseInt).collect(Collectors.toList());
        cartService.deleteCart(ids);
        return ResultVO.successResult("删除成功");
    }

    @RequestMapping(value = "count", method = RequestMethod.GET)
    public ResultVO allCount() {
        Integer id = null;
        try {
            id = getUserId();
        } catch (Exception e) {
            return ResultVO.successResult("", 0);
        }
        return ResultVO.successResult(cartService.allCount(id));
    }
}
